package com.ribbonConsumer.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.ribbonConsumer.client.UserInfoClient;
import com.ribbonConsumer.entity.UserPojo;

@RestController
public class ConsumerController {
	@Autowired
	RestTemplate restTemplate;
	
	@RequestMapping(value="/userInfo", method = RequestMethod.GET)
	public UserPojo userInfo(@RequestParam String name, @RequestParam String age) {
		//如果是post请求，可以用postForEntity
		Map<String , Object> params = new HashMap<String , Object>();
		params.put("name", name);
		params.put("age", age);
		return restTemplate.getForEntity("http://USERINFO-SERVICE/userInfo?name={name}&age={age}", 
				UserPojo.class,params).getBody();
	}
	
	/*
	 * @RequestBody告诉从body里取值，请求方的Content-Type要设置为application/json，否则报415错误
	 * @RequestBody好像不能用多个，如@RequestBody String name,@RequestBody int age
	 */
	@RequestMapping(value = "/addUserInfo", method = RequestMethod.POST)
	public String addUserInfo(@RequestBody UserPojo userPojo) {
		ResponseEntity <String> responseEntity = restTemplate.postForEntity(
				"http://USERINFO-SERVICE/addUserInfo",userPojo , String.class);
		System.err.println(responseEntity.getBody());
		return responseEntity.getBody();
	}
	
	@Autowired
	private UserInfoClient userInfoClient;
	/**
	 * 使用Feign方式调用服务
	 */
	@RequestMapping(value = "/userInfoStr", method = RequestMethod.GET)
	public String userInfoStr(@RequestParam String name, @RequestParam String age){
		return userInfoClient.userInfoStr(name, age);
	}
	
	
}
